module(..., package.seeall)
--- 模块功能：新设备发送HTTP请求获取clientNo.
-- @author zhangfenghe
-- @module Access_Control_System.getNewClientNo
-- @license MIT
-- @copyright openLuat
-- @release 2024.03.11
require "http"
require "config"
require "nvm"
require "mqttHostTask"
require "rtos"
require "logGenerator"
-- 初始化nvm获取配置参数
nvm.init("config.lua", true)
local clientNo, logInfo, errInfo, sysTime = nvm.get("ClientNo"), "", "", ""
-- 本司mqtt服务器连接任务
local function mqttHostTaskAsk() mqttHostTask.StartHostMQTTClient(clientNo) end
local function cbFnc(result, prompt, head, body)
    log.info("getNewClientNo.cbFnc", result, prompt)
    if result and head then
        for k, v in pairs(head) do
            log.info("getNewClientNo.cbFnc", k .. ": " .. v)
            logInfo = logInfo .. "[" .. sysTime .. "]" ..
                          "[getNewClientNo.cbFnc:]" .. k .. ": " .. v .. "\n"
        end
    else
        errInfo = errInfo .. "[" .. sysTime .. "]" ..
                      "获取新设备号请求头错误！" .. "\n"
    end
    if result and body then
        log.info("getNewClientNo.cbFnc", "bodyLen=" .. body:len())
        log.info("body", body)
        clientNo = body
        for i = 1, 10 do log.info("[clientNo:]" .. clientNo .. "\n") end
        logInfo =
            logInfo .. "[" .. sysTime .. "]" .. "[getNewClientNo.cbFnc:]" ..
                "bodyLen=" .. body:len() .. ",body=" .. body .. "\n"
        logGenerator.GenerateLogTask(logInfo, "log")
        nvm.set("ClientNo", clientNo)
        sys.restart("重启设备保存新生成设备号！！！")
    else
        errInfo = errInfo .. "[" .. sysTime .. "]" ..
                      "[获取新设备号请求体错误！]\n"
        logGenerator.GenerateLogTask(errInfo, "log")
    end
end

-- 获取并设置设备号
local function getAndSetClientNo()
    sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d", os.date("*t").year,
                            os.date("*t").month, os.date("*t").day,
                            os.date("*t").hour, os.date("*t").min,
                            os.date("*t").sec)
    if clientNo == "acs000000" or clientNo == nil then
        http.request("GET", "http://47.104.133.93:8090/api/genDeviceNo/acs", nil,
                     nil, nil, nil, cbFnc)
    else
        --nvm.restore()
        sys.taskInit(mqttHostTaskAsk)
    end
    if logInfo ~= "" and logInfo ~= false then
        logGenerator.GenerateLogTask(logInfo, "log")
    end
end

getAndSetClientNo()
